﻿/*
    This file is part of nDoctor Light

    NDoctor is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    NDoctor is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NDoctor.  If not, see <http://www.gnu.org/licenses/>.
*/
namespace Probel.Ldoc.ViewModels.Dto
{
    using System.Windows.Input;

    using Probel.Ldoc.Services.Services;
    using Probel.Mvvm.DataBinding;

    public abstract class TreeViewModel : BaseViewModel
    {
        #region Fields

        protected readonly IPatientService Service;

        private readonly ICommand editCommand;
        private readonly ICommand renameCommand;

        private bool isEditing;

        #endregion Fields

        #region Constructors

        public TreeViewModel(IErrorService errorService, IPatientService service, bool isAsync)
            : base(errorService, isAsync)
        {
            this.Service = service;
            this.renameCommand = new RelayCommand(this.Rename, this.CanRename);
            this.editCommand = new RelayCommand(this.Edit);
        }

        #endregion Constructors

        #region Properties

        public ICommand EditCommand
        {
            get { return this.editCommand; }
        }

        public long Id
        {
            get;
            set;
        }

        public bool IsEditing
        {
            get { return this.isEditing; }
            set
            {
                if (value) { this.CachedName = this.Name; }
                else
                {
                    this.Name = this.CachedName;
                    this.OnPropertyChanged(() => Name);
                }

                this.isEditing = value;
                this.OnPropertyChanged(() => IsEditing);
            }
        }

        public string Name
        {
            get;
            set;
        }

        public ICommand RenameCommand
        {
            get { return this.renameCommand; }
        }

        protected string CachedName
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        protected abstract void Rename();

        private bool CanRename()
        {
            return !string.IsNullOrWhiteSpace(this.Name);
        }

        private void Edit()
        {
            this.IsEditing = true;
        }

        #endregion Methods
    }
}